package cc.rboot.inject.helper;

import org.hibernate.validator.HibernateValidator;
import org.springframework.core.MethodParameter;
import org.springframework.validation.annotation.Validated;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

public class InjectValidateHelper {

    private static final Validator validatorFast = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();

    public static <T> boolean supportsValidate(MethodParameter methodParameter) {
        return methodParameter.getParameter().isAnnotationPresent(Validated.class)
                || methodParameter.getParameter().isAnnotationPresent(Valid.class)
                || methodParameter.getMethod().getDeclaringClass().isAnnotationPresent(Validated.class)
                || methodParameter.getMethod().getDeclaringClass().isAnnotationPresent(Valid.class);
    }


    public static <T> void validate(T entity) throws Exception {
        Set<ConstraintViolation<Object>> validateResult = validatorFast.validate(entity);
        if (validateResult.size() > 0) {
            String msg = validateResult.iterator().next().getPropertyPath() + "：" + validateResult.iterator().next().getMessage();
            throw new Exception(msg);
        }
    }
}